package com.xq.service.impl;

import com.xq.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
/**
 * 验证码服务实现接口
 */
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 验证码失效时间
     */
    private static final long CODE_EXPIRE_SECONDS = 300;

    //TODO 后期需要实现短信发送的服务
    @Override
    public void sendVerificationCode(String phone) {
        // 生成6位随机数字
        String code = String.format("%06d", new Random().nextInt(999999));

        // 存储到Redis（实际需要配置Redis）
        //TiemUtils是单位
        redisTemplate.opsForValue().set(
                "SMS_CODE:" + phone,
                code,
                CODE_EXPIRE_SECONDS,
                TimeUnit.SECONDS
        );

        // 模拟发送短信（实际需要接入短信网关）
        System.out.println("发送短信验证码到 " + phone + "，验证码：" + code);


    }

    //验证码验证
    @Override
    public boolean validateCode(String phone, String code) {
        String redisCode = (String) redisTemplate.opsForValue().get("SMS_CODE:" + phone);
        if (redisCode == null || !redisCode.equals(code)) {
            return false;
        }
        return true;
    }
}
